// ** Step 6: Create Datacontext Service **//
(function () {
    'use strict';

    var serviceId = 'datacontext';
    angular.module('app').factory(serviceId, ['$rootScope', '$resource','spappcontext','common', datacontext]);

    function datacontext($rootScope,$resource, spappcontext,common) {
        var $q = common.$q;

        //load the host web and app web urls 

        /*
        ShareCoffee.Commons.loadHostWebUrlFrom = spappcontext.hostWeb.SPHostUrl;
        var hostWebUrl = ShareCoffee.Commons.getHostWebUrl();
        ShareCoffee.Commons.loadAppWebUrlFrom = spappcontext.hostWeb.SPAppWebUrl;
        var appWebUrl = ShareCoffee.Commons.getAppWebUrl();
        */

        var service = {
            getPeople: getPeople,
            getMessageCount: getMessageCount,
            getUserName: getUserName,
            getCustomers: getCustomers,
            getSPContacts: getSPContacts
            
        };

        return service;

        function getMessageCount()
        {
            return $q.when(72);
        }

        function getPeople() {
            var people = [
                { firstName: 'John', lastName: 'Papa', age: 25, location: 'Florida' },
                { firstName: 'Ward', lastName: 'Bell', age: 31, location: 'California' },
                { firstName: 'Colleen', lastName: 'Jones', age: 21, location: 'New York' },
                { firstName: 'Madelyn', lastName: 'Green', age: 18, location: 'North Dakota' },
                { firstName: 'Ella', lastName: 'Jobs', age: 18, location: 'South Dakota' },
                { firstName: 'Landon', lastName: 'Gates', age: 11, location: 'South Carolina' },
                { firstName: 'Haley', lastName: 'Guthrie', age: 35, location: 'Wyoming' }
            ];
            return $q.when(people);
        }

        function getCustomers() {

            var dfd = $q.defer();
            var webApi = $resource('http://customerwebapi.cloudapp.net/api/Customer/:Id', { Id: "@Id" }, { update: { method: 'PUT' } });
         //   var webApi = $resource('http://localhost/AppWeb/api/Customer/:Id', { Id: "@Id" }, { update: { method: 'PUT' } });
            webApi.query(function(data){
                var customers = data;
                customers.splice(4, 847)
                dfd.resolve(customers);
            },function(error){
                console.log(error);
                dfd.reject(error);
            });
            return dfd.promise;
        }

        function getUserName() {

            var dfd = $q.defer();

            // Standard function to get hostweb
            var ctx = new SP.ClientContext(spappcontext.hostWeb.SPAppWebUrl);
            var factory = new SP.ProxyWebRequestExecutorFactory(spappcontext.hostWeb.SPAppWebUrl);
            ctx.set_webRequestExecutorFactory(factory);
            var hostWebctx = new SP.AppContextSite(ctx, spappcontext.hostWeb.SPHostUrl);

                var appWeb = ctx.get_web();
                var hostWeb = hostWebctx.get_web();
                var currentAppWebUser = appWeb.get_currentUser();
                var currentHostWebUser = hostWeb.get_currentUser();

                ctx.load(appWeb);
                ctx.load(hostWeb);
                ctx.load(currentAppWebUser);
                ctx.load(currentHostWebUser);

                ctx.executeQueryAsync(function () {
                    var userName = currentAppWebUser.get_title();
                    dfd.resolve(userName);
                }, function (sender, args) {
                    console.log(args.get_message() + " " + args.get_stackTrace());
                    dfd.reject(args.get_message());
                });

             return dfd.promise;
        }

        function getSPContacts()
        {
            
            var dfd = $q.defer();
            
            // Standard function to get hostweb
            var ctx = new SP.ClientContext(spappcontext.hostWeb.SPAppWebUrl);
            var factory = new SP.ProxyWebRequestExecutorFactory(spappcontext.hostWeb.SPAppWebUrl);
            ctx.set_webRequestExecutorFactory(factory);
            var hostWebctx = new SP.AppContextSite(ctx, spappcontext.hostWeb.SPHostUrl);

            var appWeb = ctx.get_web();
            var hostWeb = hostWebctx.get_web();

                var ContactList = hostWeb.get_lists().getByTitle('DemoCustomer');
                var contactListItems = ContactList.getItems(SP.CamlQuery.createAllItemsQuery());
                ctx.load(ContactList);
                ctx.load(contactListItems);
                ctx.executeQueryAsync(function () {
                    var enumerator = contactListItems.getEnumerator();
                    var SPContacts = [];
                    while (enumerator.moveNext()) {
                        var currentItem = enumerator.get_current();
                        SPContacts.push({ "FirstName": currentItem.get_item('FirstName'), "LastName": currentItem.get_item('Title') });
                    }
                    var SPContactsObj = SPContacts;

                    dfd.resolve(SPContactsObj);
                }, function (sender, args) {
                    console.log(args.get_message() + " " + args.get_stackTrace());
                    dfd.reject(args.get_message());
                });
            return dfd.promise;
        }
    }
})();